package com.netty.client;

import com.message.Message;
import com.netty.ServerAddress;
import com.netty.channel.ChannelAttribute;
import com.netty.channel.ChannelVector;
import com.protocol.ss.SSProtocol.SSRegister;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;

/**
 * client的一个netty连接
 * 
 * @author zhoufang
 *
 *         2017年12月24日下午6:25:06
 */
public class ClientNettyConnect {

	/** 连接的服务器地址信息 */
	private ServerAddress serverAddress = null;

	/** 所有channel */
	private ChannelVector channels = new ChannelVector();

	public ClientNettyConnect(ServerAddress serverAddress) {
		this.serverAddress = serverAddress;
	}

	/**
	 * 随机获取一个channel
	 * 
	 * @return
	 */
	public Channel randomChannel() {
		return this.channels.randomChannel();
	}

	/**
	 * 增加一个channel
	 * 
	 * @param channel
	 */
	public void addChannel(Channel channel) {
		System.out.println("连接 serverId="+getServerId()+" 成功, 记录新channel="+channel.toString());
		channel.attr(ChannelAttribute.SS_CLIENT_ID).set(getServerId());
		this.channels.addChannel(channel);
		
		// 发送注册信息
		SSRegister.Builder builder = SSRegister.newBuilder();
		builder.setServerId(10);
		Message msg = Message.createMessage(1, 2, builder.build());
		channel.writeAndFlush(msg);
	}

	/**
	 * 连接
	 */
	public void connect() {
		ChannelFuture future = ClientNettyManager.getBootstrap().connect(
				serverAddress.getServerIp(), serverAddress.getServerPort());
		future.addListener(new NettyConnectListener(this));
	}
	
	/**
	 * 断线重连
	 * @param channel  被断开的channel
	 */
	public void reConnect(Channel channel) {
		System.out.println("serverId="+getServerId()+" 的channel="+channel.toString()+" 断开,启动重连");
		this.channels.removeChannel(channel);
		connect();
	}
	
	
	public int getServerId() {
		return this.serverAddress.getServerId();
	}

	public ServerAddress getServerAddress() {
		return serverAddress;
	}


}
